package cn.edu.ncut.cs.springboot.petmanagementsystem.service.Impl;

import cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.*;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.*;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.SearchService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 搜索服务实现类
 */
@Service
@RequiredArgsConstructor
public class SearchServiceImpl implements SearchService {
    
    private final SearchHistoryMapper searchHistoryMapper;
    private final ProductMapper productMapper;
    private final ServiceTypeMapper serviceTypeMapper;
    private final PetCareRecordMapper petCareRecordMapper;
    
    @Override
    @Transactional
    public Map<String, Object> globalSearch(String keyword, String type, Long userId) {
        Map<String, Object> result = new HashMap<>();
        
        // 记录搜索历史
        if (userId != null) {
            recordSearchHistory(userId, keyword, type);
        }
        
        if ("all".equals(type) || "product".equals(type)) {
            // 搜索商品
            LambdaQueryWrapper<Product> productWrapper = new LambdaQueryWrapper<>();
            productWrapper.and(w -> w.like(Product::getProductName, keyword)
                    .or().like(Product::getDescription, keyword))
                    .eq(Product::getProductStatus, 1)
                    .orderByDesc(Product::getSoldQuantity);
            List<Product> products = productMapper.selectList(productWrapper);
            result.put("products", products);
        }
        
        if ("all".equals(type) || "service".equals(type)) {
            // 搜索服务类型
            LambdaQueryWrapper<ServiceType> serviceWrapper = new LambdaQueryWrapper<>();
            serviceWrapper.and(w -> w.like(ServiceType::getServiceName, keyword)
                    .or().like(ServiceType::getDescription, keyword))
                    .eq(ServiceType::getStatus, 1);
            List<ServiceType> services = serviceTypeMapper.selectList(serviceWrapper);
            result.put("services", services);
        }
        
        return result;
    }
    
    @Override
    public List<String> getSearchSuggestions(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return Collections.emptyList();
        }
        
        // 从搜索历史中获取建议
        LambdaQueryWrapper<SearchHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(SearchHistory::getKeyword, keyword)
                .groupBy(SearchHistory::getKeyword)
                .orderByDesc(SearchHistory::getSearchCount)
                .last("LIMIT 10");
        
        List<SearchHistory> histories = searchHistoryMapper.selectList(wrapper);
        
        return histories.stream()
                .map(SearchHistory::getKeyword)
                .distinct()
                .collect(Collectors.toList());
    }
    
    @Override
    public List<String> getHotSearches(int limit) {
        return searchHistoryMapper.getHotKeywords(limit);
    }
    
    @Override
    public List<SearchHistory> getUserSearchHistory(Long userId, int limit) {
        return searchHistoryMapper.getUserSearchHistory(userId, limit);
    }
    
    @Override
    @Transactional
    public void clearUserSearchHistory(Long userId) {
        LambdaQueryWrapper<SearchHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SearchHistory::getUserId, userId);
        searchHistoryMapper.delete(wrapper);
    }
    
    @Override
    @Transactional
    public void recordSearchHistory(Long userId, String keyword, String type) {
        // 查询是否已存在该搜索记录
        LambdaQueryWrapper<SearchHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SearchHistory::getUserId, userId)
                .eq(SearchHistory::getKeyword, keyword)
                .eq(SearchHistory::getSearchType, type);
        
        SearchHistory existing = searchHistoryMapper.selectOne(wrapper);
        
        if (existing != null) {
            // 更新搜索次数
            existing.setSearchCount(existing.getSearchCount() + 1);
            existing.setUpdateTime(LocalDateTime.now());
            searchHistoryMapper.updateById(existing);
        } else {
            // 新增搜索记录
            SearchHistory history = new SearchHistory();
            history.setUserId(userId);
            history.setKeyword(keyword);
            history.setSearchType(type);
            history.setSearchCount(1);
            history.setCreateTime(LocalDateTime.now());
            history.setUpdateTime(LocalDateTime.now());
            searchHistoryMapper.insert(history);
        }
    }
}
